<template>
  <div>
    <!-- 头部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面板 -->
    <el-card class="box-card">
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            @clear="cleart"
            clearable
            v-model="goodData.query"
          >
            <el-button
              slot="append"
              @click="search"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table :data="list" style="width: 100%" stripe border>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="“状态" width="180">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="state(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" width="180">
          <template slot-scope="scope">
            <!-- 修改信息 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="amchange(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="movedgit(scope.row.id)"
            >
            </el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="setrolesbox(scope.row)"
                type="warning"
                size="mini"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="goodData.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="goodData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 弹出框 -->
      <el-dialog
        @close="resetForm"
        title="添加信息"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <!-- 主题表单 -->
        <el-form ref="forms" :model="addform" :rules="rules" label-width="80px">
          <el-form-item label="用户名" prop="addname">
            <el-input v-model="addform.addname"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="addpaw">
            <el-input v-model="addform.addpaw"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="addemail">
            <el-input v-model="addform.addemail"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="addphone">
            <el-input v-model="addform.addphone"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="check">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改弹出框 -->
      <el-dialog
        title="修改信息"
        :visible.sync="chan"
        @close="resets"
        width="50%"
      >
        <!-- 修改表单 -->
        <el-form
          ref="elRef"
          :model="changform"
          :rules="changRules"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input v-model="changform.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="changform.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="changform.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="chan = false">取 消</el-button>
          <el-button type="primary" @click="changeds">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配角色弹框 -->
    <el-dialog title="分配角色" :visible.sync="setrolesberool" width="50%"
    @close='boxclose' 
    >
      <span>
        <p>当前用户 ：{{ userinfo.username }}</p>
        <p>当前角色：&nbsp; {{ userinfo.role_name }}</p>
        <P
          >分配新角色：&nbsp;
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in listdataselece"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </P>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setrolesberool = false">取 消</el-button>
        <el-button type="primary" @click="rolseboxcolse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 添加自定义验证
    var checkemail = (rule, value, cb) => {
      const regemail = /^\w+@\w+(\.\w+)+$/;
      if (regemail.test(value)) {
        return cb();
      }
      cb(new Error("填写正确信息"));
    };
    var checkphone = (rule, value, cb) => {
      const regphone = /^1[34578]\d{9}$/;

      if (regphone.test(value)) {
        return cb();
      }
      cb(new Error("填写正确信息"));
    };

    return {
      id: "",
      // 下拉菜单和数据
      listdataselece: [],
      value: "",
      // 分配角色berool
      setrolesberool: false,
      // 分配角色信息
      userinfo: {},
      // 表单
      addform: {
        addname: "",
        addpaw: "",
        addemail: "",
        addphone: "",
      },
      // 修改表单
      changform: {
        id: "",
        username: "",
        email: "",
        mobile: "",
      },
      // 修改验证表单
      changRules: {
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkphone, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkemail, trigger: "blur" },
        ],
      },
      // 表单验证
      rules: {
        addname: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        addpaw: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
        addemail: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkemail, trigger: "blur" },
        ],
        addphone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkphone, trigger: "blur" },
        ],
      },
      // 弹出框
      dialogVisible: false,
      //  修改i爱弹出框
      chan: false,
      goodData: {
        query: "",
        // 第几页几页
        pagenum: 1,
        // 每页几条
        pagesize: 2,
      },
      list: [],
      total: 0,
    };
  },

  created() {
    this.query();
  },
  methods: {
    async query() {
      const { data: res } = await this.$http.get("users", {
        params: this.goodData,
      });
      // console.log(res);
      // console.log(res.data.total);
      if (res.meta.status !== 200) {
        this.$message.error("获取失败");
      }
      this.list = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      // console.log(val);
      this.goodData.pagesize = val;
      this.query();
    },
    handleCurrentChange(val) {
      // console.log(val);
      this.goodData.pagenum = val;
      this.query();
    },
    async state(val) {
      // console.log(val);
      const { data: res } = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改失败");
      }
      // console.log(res);
      this.query();
      this.$message.success("修改成功");
    },
    search() {
      this.query();
    },
    cleart() {
      this.query();
    },
    // 添加表单验证
    resetForm() {
      // console.log(1111);
      this.$refs.forms.resetFields();
    },
    // 请求增加数据 和整个表单校验
    check() {
      this.$refs.forms.validate(async (val) => {
        if (!val) {
          return this.$message.error("添加失败");
        }
        const { data: res } = await this.$http.post("users", {
          username: this.addform.addname,
          password: this.addform.addpaw,
          email: this.addform.addemail,
          mobile: this.addform.addphone,
        });
        console.log(res);
        this.query();
      });

      this.dialogVisible = false;
    },
    async amchange(id) {
      this.chan = true;
      const { data: res } = await this.$http.get("users/" + id);
      console.log(res, "....");
      this.changform.username = res.data.username;
      this.changform.email = res.data.email;
      this.changform.mobile = res.data.mobile;
      this.changform.id = res.data.id;
    },
    // 重置
    resets() {
      this.$refs.elRef.resetFields();
    },
    // 修改确定
    changeds() {
      this.$refs.elRef.validate(async (val) => {
        if (!val) {
          return;
        }
        const { data: res } = await this.$http.put(
          "users/" + this.changform.id,
          this.changform
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        this.$message.success("修改成功");
        this.query();
      });
      this.chan = false;
    },
    // 删除用户
    async moved(id) {
      const del = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "删除用户",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        if (del !== "confirm") {
          return this.$message.info("取消删除");
        }
      });
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.query();
    },
    // 分配角色弹出框
    async setrolesbox(roles) {
      // console.log(roles);
      this.id = roles.id;
      this.userinfo.username = roles.username;
      this.userinfo.role_name = roles.role_name;
      //  发起角色列表请求
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      this.listdataselece = res.data;

      this.setrolesberool = true;
    },
    // 分配角色弹框关闭
    async rolseboxcolse() {
      const { data: res } = await this.$http.put("users/" + this.id + "/role", {
        rid: this.value,
      });
      console.log(res, "000");
      if (res.meta.status !== 200) {
        return this.$message.error("分配角色错误");
      }
      this.$message.success("分配角色成功");
      this.query();
      this.setrolesberool = false;
    },
    // 分配角色重置
    boxclose(){
     this.value=''
     this.userinfo={}
    },
    // 删除角色

    movedgit() {
      console.log(111);
    },
  },
};
</script>

<style lang="less" scoped>
</style>